
/*************************************************************
	Class:		flexiGrid
	Version:	1.0
	Author:		Samuel Birch
*************************************************************/
var flexiGrid = new Class({
	
	Implements: [Options,Events,Chain],
	
	getOptions: function(){
		return {
			transition: 'sine:in:out',
			duration: 500,
			config: null,
			onOpen: $lambda(false),
			onClose: $lambda(false),
			onClick: $lambda(false)
		};
	},
	
	initialize: function(elements, options){
		this.setOptions(this.getOptions(), options);
		
		this.elements = $$(elements);
		if(this.options.config){
			new Request.JSON({'url':this.options.config, onSuccess:function(json, txt){
				this.config = JSON.decode(txt);
			}.bind(this)}).get();
		}
		
		this.fxOptions = {
			link: 'cancel',
			duration: this.options.duration, 
			transition: this.options.transition
		};
		
		this.defaults = [];
		this.elements.each(function(el,i){
			this.defaults.push(el.getStyles('top', 'left', 'width', 'height'));
		}, this);
		
		this.fx = new Fx.Elements(this.elements, this.fxOptions);
		
		
		
		this.elements.each(function(el,i){
			var id = el.get('id');
			el.addEvents({
				'mouseenter': function(e){
					this.open(id);
					this.fireEvent('onOpen', [id, i]);
				}.bind(this),
				'mouseleave': function(e){
					this.close(id);
					this.fireEvent('onClose', [id, i]);
				}.bind(this),
				'onClick': function(e){
					this.fireEvent('onClick', [id, i]);
				}.bind(this)
			});
		}, this);
	},
	
	open: function(id){
		var obj = {};
		this.defaults.each(function(el,i){
			var o = {};
			obj[i] = o
			for(var item in el){
				o[item] = el[item];
			}
		});
		
		var c = this.getConfig(id);
		if(c){
			var pos = this.getPosition(id);
			for(var item in c.props){
				obj[pos][item] = c.props[item];
			}
			c.affects.each(function(el,i){
				var pos = this.getPosition(el.id);
				for(var item in el.props){
					obj[pos][item] = el.props[item];
				}
			}, this);
			this.fx.start(obj);
			
			if(c.events){
				if(c.events.onOpen){
					c.events.onOpen();
				}
			}
		}
		
	},
	
	close: function(id){
		var obj = {};
		this.defaults.each(function(el,i){
			obj[i] = el;
		},this);
		this.fx.start(obj);
		
		var c = this.getConfig(id);
		if(c){
			if(c.events){
				if(c.events.onClose){
					c.events.onClose();
				}
			}
		}
	},
	
	getPosition: function(id){
		var pos = null;
		this.elements.each(function(el, i){
			if(el.get('id') == id){
				pos = i;
			}
		});
		return pos;
	},
	
	getConfig: function(id){
		var obj = null;
		this.config.each(function(el,i){
			if(el.id == id){
				obj = el;
			}
		});
		return obj;
	},
	
	getDefaults: function(id){
		this.defaults.each(function(el,i){
			if(el.id == id){
				return el.coords;
			}
		});
	}
});